package com.androidx.paging.datasource

import androidx.paging.ItemKeyedDataSource
import com.androidx.paging.model.GoodsModel

/**
 * Created by zhangyuncai on 2020/8/6.
 * ItemKeyedDataSource：按条目加载，即请求数据需要传入其它item的信 息，如加载第n+1项的数据需传入第n项的id
 */
//按条目加载，即请求数据需要传入其它item的信息，如加载第n+1项的数据需传入第n项的id
class GoodsItemDataSource:ItemKeyedDataSource<Int, GoodsModel>() {
    //初次加载
    override fun loadInitial(
        params: LoadInitialParams<Int>,
        callback: LoadInitialCallback<GoodsModel>
    ) {
        val datas = setDatas(0)
        callback.onResult(datas,0,20)
    }
    //滑到底部加载数据
    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<GoodsModel>) {
        val datas = setDatas(params.key)
        callback.onResult(datas)
    }
    //滑倒顶部加载数据
    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<GoodsModel>) {
        val datas = setDatas(params.key)
        callback.onResult(datas)
    }
    //获取key
    override fun getKey(item: GoodsModel): Int {
        return item.id
    }

    private fun setDatas(key:Int): List<GoodsModel> {
        val datas = mutableListOf<GoodsModel>()
        for (index in key + 1..(key + 1) + 10) {
            datas.add(GoodsModel().apply {
                id = index
                name = "商品名:${index}"
            })
        }
        return datas
    }
}